package com.k8.registry;

import com.k8.common.aware.BeanFactoryAware;
import com.k8.common.factroy.BeanFactory;
import com.k8.common.factroy.loader.ExtensionLoader;
import com.k8.common.ioc.Required;
import com.k8.rpc.registry.Registry;
import com.k8.rpc.registry.RegistryFactory;
import com.k8.rpc.url.URL;

import javax.annotation.Resource;
import java.util.concurrent.locks.Lock;

public class ServiceDiscoverRegistryFactory extends AbstractRegistryFactory implements BeanFactoryAware {

    @Resource
    @Required
    RegistryManager registryManager;
    BeanFactory beanFactory;

    @Override
    public void beanFactoryAware(BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    @Override
    public Registry getRegistry(URL url) {
        //协议头转换
        url.setProtocol(url.getRegistryName());
        if (this.registryManager == null) throw new RegistryException("RegistryManger is null");
        Registry registry = registryManager.getCacheRegistry().get(url.getProtocol());
        if (registry == null) {
            Lock lock = registryManager.getLock();
            try {
                lock.lock();
                registry = createRegistry(url, beanFactory);
                registryManager.putRegistry(url.getProtocol(), registry);
            } catch (RuntimeException e) {
                lock.unlock();
                throw new RegistryException(e.getMessage());
            }
        }
        return registry;
    }

    private Registry createRegistry(URL registryUrl, BeanFactory beanFactory) {
        ExtensionLoader<RegistryFactory> extensionLoader = beanFactory.getExtensionDirector().getExtensionLoader(RegistryFactory.class);
        RegistryFactory registryFactory = extensionLoader.getExtension(registryUrl.getProtocol());
        return registryFactory.getRegistry(registryUrl);
    }

}
